#include "Device.h"
#include "D3DException.h"
#include "Color.h"
//Core
#include "NeroCore\NMemoryManager.h"
//Engine
#include "NeroEngine\NFileSystem.h"
#include "NeroEngine\NInput.h"
#include "NeroEngine\NRenderThread.h"
//Game
#include "NeroGame\NGame.h"

extern Engine::NInput* GInput;

using namespace Graphics;

RTTI_DEFINITIONS(D3DDevice)

#ifdef DX_11
#include "D3DX10math.h"

POINT CenterWindow(int windowWidth, int windowHeight)
{
	POINT newPoint;
	newPoint.x = (GetSystemMetrics(SM_CXSCREEN) - windowWidth)/2;
	newPoint.y = (GetSystemMetrics(SM_CYSCREEN) - windowHeight)/2;
	return newPoint;
}

D3DDevice::D3DDevice(Engine::NPlatform* owner)
	:Engine::NDevice(owner),
	 mDevice(NULL),
 	 mDeviceContext(NULL),
	 mRenderTargetView(NULL),
	 mDepthStencilBuffer(NULL),
	 mDepthStencilView(NULL),
	 mIsFullscreen(FULL_SCREEN)
{

	mRenderState.AlphaDisableBlendingState = NULL;
	mRenderState.AlphaEnableBlendingState = NULL;
	mRenderState.DepthDisabledStencilState = NULL;
	mRenderState.DepthStencilState = NULL;
	mRenderState.RasterizerState = NULL;
}


D3DDevice::~D3DDevice(void)
{
	Deinitialize();
}

void D3DDevice::Initialize(HINSTANCE instance, int showCommand)
{
	NDevice::Initialize();

	mWindowsSettings.Instance = instance;
	mGraphicsSettings.ShowCommand = showCommand;

	InitWindowHandle();
	InitD3DDevice();

	// Setup the projection matrix.
	float fieldOfView = (float)D3DX_PI / 4.0f;
	float screenAspect = (float)mResolution.ScreenWidth / (float)mResolution.ScreenHeight;

	// Create the projection matrix for 3D rendering.
	D3DXMatrixPerspectiveFovLH(&mProjectionMatrix, fieldOfView, screenAspect, SCREEN_NEAR, SCREEN_DEPTH);

    // Initialize the world matrix to the identity matrix.
    D3DXMatrixIdentity(&mWorldMatrix);

	// Create an orthographic projection matrix for 2D rendering.
	D3DXMatrixOrthoLH(&mOrthoMatrix, (float)mResolution.ScreenWidth, (float)mResolution.ScreenHeight, SCREEN_NEAR, SCREEN_DEPTH);
}

void D3DDevice::Deinitialize()
{
	// Before shutting down set to windowed mode or when you release the swap chain it will throw an exception.
	if(mSwapChain)
	{
		mSwapChain->SetFullscreenState(false, NULL);
	}

	if(mSwapChain)
	{
		mSwapChain->Release();
		mSwapChain = NULL;
	}

	if(mRenderTargetView)
	{
		mRenderTargetView->Release();
		mRenderTargetView = NULL;
	}

	if(mDepthStencilView)
	{
		mDepthStencilView->Release();
		mDepthStencilView = NULL;
	}

	if(mDepthStencilBuffer)
	{
		mDepthStencilBuffer->Release();
		mDepthStencilBuffer = NULL;
	}

	if(mRenderState.AlphaDisableBlendingState)
	{
		mRenderState.AlphaDisableBlendingState->Release();
		mRenderState.AlphaDisableBlendingState = NULL;
	}

	if(mRenderState.AlphaEnableBlendingState)
	{
		mRenderState.AlphaEnableBlendingState->Release();
		mRenderState.AlphaEnableBlendingState = NULL;
	}

	if(mRenderState.DepthDisabledStencilState)
	{
		mRenderState.DepthDisabledStencilState->Release();
		mRenderState.DepthDisabledStencilState = NULL;
	}

	if(mRenderState.DepthStencilState)
	{
		mRenderState.DepthStencilState->Release();
		mRenderState.DepthStencilState = NULL;
	}

	if(mRenderState.RasterizerState)
	{
		mRenderState.RasterizerState->Release();
		mRenderState.RasterizerState = NULL;
	}

	if(mDeviceContext)
	{
		mDeviceContext->Release();
		mDeviceContext = NULL;
	}

	if(mDevice)
	{
#ifdef _DEBUG
		mDevice->QueryInterface(__uuidof(ID3D11Debug), reinterpret_cast<void**>(&mD3D_Debug));
		
#endif		
		mDevice->Release();
#ifdef _DEBUG
		mD3D_Debug->ReportLiveDeviceObjects(D3D11_RLDO_DETAIL);
		mD3D_Debug->Release();
#endif		
		mDevice = NULL;
	}	
}

void D3DDevice::InitWindowHandle()
{
	WNDCLASSEX WindowDesc;

	//Screen width and height set
	mResolution.ScreenWidth = 1280;
	mResolution.ScreenHeight = 720;
	
	mWindowsSettings.WindowTitle = "Nero Engine DX11";
	mWindowsSettings.WindowClass = "Nero Engine";

	// clear out the window class for use
	ZeroMemory(&WindowDesc, sizeof(WNDCLASSEX));

	  // fill in the struct with the needed information (PROBABLY DONT NEED TO SAVE)
	WindowDesc.cbSize = sizeof(WNDCLASSEX);
	WindowDesc.style = CS_HREDRAW | CS_VREDRAW | CS_NOCLOSE;
	WindowDesc.lpfnWndProc = WndProc;
	WindowDesc.cbClsExtra = NULL;
	WindowDesc.cbWndExtra = NULL;
	WindowDesc.hInstance = mWindowsSettings.Instance;
	WindowDesc.hIcon = LoadIcon(0, IDI_WINLOGO);
    WindowDesc.hCursor = LoadCursor(NULL, IDC_ARROW);
    WindowDesc.hbrBackground = (HBRUSH)COLOR_WINDOW;
	WindowDesc.lpszClassName = mWindowsSettings.WindowClass;

	 // register the window class
    if (!RegisterClassEx(&WindowDesc))
	{
		MessageBox(NULL, "Error registering class",	"Error", MB_OK | MB_ICONERROR);
		return;
	}

	  // create the window and use the result as the handle
	POINT windowLocation = CenterWindow(mResolution.ScreenWidth,mResolution.ScreenHeight);
	mWindowsSettings.WindowHandle = CreateWindowEx (	WS_EX_APPWINDOW,
														mWindowsSettings.WindowClass,				// name of the window class
														mWindowsSettings.WindowTitle,				// title of the window
														WS_CLIPSIBLINGS | WS_CLIPCHILDREN | WS_POPUP/*WS_OVERLAPPEDWINDOW*/,						// window style
														windowLocation.x,							// x-position of the window
														windowLocation.y,							// y-position of the window
														mResolution.ScreenWidth,					// width of the window
														mResolution.ScreenHeight,					// height of the window
														NULL,										// we have no parent window, NULL
														NULL,										// we aren't using menus, NULL
														mWindowsSettings.Instance,					// application handle
														NULL	);									// used with multiple windows, NULL
	if (!mWindowsSettings.WindowHandle)
	{
		throw D3DException("Error creating window");
	}

	ShowWindow(mWindowsSettings.WindowHandle, mGraphicsSettings.ShowCommand); // display the window on the screen
	SetForegroundWindow(mWindowsSettings.WindowHandle);
	SetFocus(mWindowsSettings.WindowHandle);

	ShowCursor(true);
}

void D3DDevice::InitD3DDevice()
{
	// Set the feature level to DirectX 11.
	mWindowsSettings.FeatureLevel = D3D_FEATURE_LEVEL_11_0;
	//V-Sync
	mGraphicsSettings.VsyncEnabled  = VSYNC_ENABLED;
	

	if(SetupGraphicCardInfo())
	{
		LOGD("SetupGraphicCardInfo");
	}	

	if(SetupSwapChain())
	{	
		LOGD("SetupSwapChain");
	}
	
	if(SetupBackBuffer())
	{
		LOGD("SetupBackBuffer");
	}

	if(SetupDepthStencil())
	{
		LOGD("SetupDepthStencil");
	}
	
	if(SetupRasterizer())
	{
		LOGD("SetupRasterizer");
	}
	
	if(SetupAlphaBlend())
	{
		LOGD("SetupAlphaBlend");
	}

	// Set Render Target
	mDeviceContext->OMSetRenderTargets(1, &mRenderTargetView, mDepthStencilView);
}

bool D3DDevice::SetupGraphicCardInfo()
{
	HRESULT result;
	IDXGIFactory* factory;
	IDXGIAdapter* adapter;
	IDXGIOutput* adapterOutput;
	unsigned int numModes, i, stringLength;
	DXGI_MODE_DESC* displayModeList;
	DXGI_ADAPTER_DESC adapterDesc;
	
	// Create a DirectX graphics interface factory.
	result = CreateDXGIFactory(__uuidof(IDXGIFactory), (void**)&factory);
	CHECK(result);

	// Use the factory to create an adapter for the primary graphics interface (video card).
	result = factory->EnumAdapters(0, &adapter);
	CHECK(result);

	// Enumerate the primary adapter output (monitor).
	result = adapter->EnumOutputs(0, &adapterOutput);
	CHECK(result);

	// Get the number of modes that fit the DXGI_FORMAT_R8G8B8A8_UNORM display format for the adapter output (monitor).
	result = adapterOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_ENUM_MODES_INTERLACED, &numModes, NULL);
	CHECK(result);

	// Create a list to hold all the possible display modes for this monitor/video card combination.
	displayModeList = new DXGI_MODE_DESC[numModes];
	if(!displayModeList)
	{
		return false;
	}

	// Now fill the display mode list structures.
	result = adapterOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_ENUM_MODES_INTERLACED, &numModes, displayModeList);
	CHECK(result);

	// Now go through all the display modes and find the one that matches the screen width and height.
	// When a match is found store the numerator and denominator of the refresh rate for that monitor.
	for(i=0; i<numModes; i++)
	{
		if(displayModeList[i].Width == (unsigned int)mResolution.ScreenWidth)
		{
			if(displayModeList[i].Height == (unsigned int)mResolution.ScreenHeight)
			{
				mResolution.ScreenNumerator = displayModeList[i].RefreshRate.Numerator;
				mResolution.ScreenDenominator = displayModeList[i].RefreshRate.Denominator;
			}
		}
	}

	// Get the adapter (video card) description.
	result = adapter->GetDesc(&adapterDesc);
	CHECK(result);

	// Store the dedicated video card memory in megabytes.
	mResolution.VideoCardMemory = (int)(adapterDesc.DedicatedVideoMemory / 1024 / 1024);

	// Convert the name of the video card to a character array and store it.
	wcstombs_s(&stringLength, mResolution.VideoCardDescription, 128, adapterDesc.Description, 128);
	
	// Release the display mode list.
	delete [] displayModeList;
	displayModeList = 0;

	// Release the adapter output.
	adapterOutput->Release();
	adapterOutput = 0;

	// Release the adapter.
	adapter->Release();
	adapter = 0;

	// Release the factory.
	factory->Release();
	factory = 0;
	return true;
}

Resolution D3DDevice::GetResolutionInfo()
{
	return mResolution;
}

WindowsSettings D3DDevice::GetWindowsSettings()
{
	return mWindowsSettings;
}

bool D3DDevice::SetupSwapChain()
{
	HRESULT result;
	DXGI_SWAP_CHAIN_DESC swapChainDesc;
	ZeroMemory(&swapChainDesc, sizeof(swapChainDesc));			// Initialize the swap chain description.
	

	UINT creationFlags = D3D11_CREATE_DEVICE_BGRA_SUPPORT;
#ifdef _DEBUG
	creationFlags = D3D11_CREATE_DEVICE_DEBUG;
#endif

	swapChainDesc.BufferCount = 1;					//Set to a single back buffer
	swapChainDesc.BufferDesc.Width = mResolution.ScreenWidth;
	swapChainDesc.BufferDesc.Height = mResolution.ScreenHeight;
	
	if(mGraphicsSettings.VsyncEnabled)				// Set the refresh rate of the back buffer.
	{
		swapChainDesc.BufferDesc.RefreshRate.Numerator = mResolution.ScreenNumerator;
		swapChainDesc.BufferDesc.RefreshRate.Denominator = mResolution.ScreenDenominator;
	}
	else
	{
		swapChainDesc.BufferDesc.RefreshRate.Numerator = 0;
		swapChainDesc.BufferDesc.RefreshRate.Denominator = 1;
	}

	swapChainDesc.BufferDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;
	swapChainDesc.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
	swapChainDesc.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED;
	swapChainDesc.SampleDesc.Count = 1;
	swapChainDesc.SampleDesc.Quality = 0;
	swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
	swapChainDesc.OutputWindow = mWindowsSettings.WindowHandle;
	swapChainDesc.Windowed = !mIsFullscreen;
	swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
	swapChainDesc.Flags = 0;


	result = D3D11CreateDeviceAndSwapChain( NULL,
											D3D_DRIVER_TYPE_HARDWARE, 
											NULL, 
											creationFlags, 
											&mWindowsSettings.FeatureLevel, 
											1, 
											D3D11_SDK_VERSION,
											&swapChainDesc,
											&mSwapChain,
											&mDevice,
											NULL,
											&mDeviceContext);
	CHECK(result);

	ID3D11Texture2D* backBuffer = NULL;
	result = mSwapChain->GetBuffer(0, _uuidof(ID3D11Texture2D), (LPVOID*)&backBuffer);
	CHECK(result);

	result = mDevice->CreateRenderTargetView(backBuffer, 
											 NULL, 
											 &mRenderTargetView);
	CHECK(result);

	backBuffer->Release();
	return true;
}

bool D3DDevice::SetupBackBuffer()
{
	HRESULT result;
	D3D11_TEXTURE2D_DESC depthBufferDesc;
	// Initialize the description of the depth buffer.
	ZeroMemory(&depthBufferDesc, sizeof(depthBufferDesc));

	// Set up the description of the depth buffer.
	depthBufferDesc.Width = mResolution.ScreenWidth;
	depthBufferDesc.Height = mResolution.ScreenHeight;
	depthBufferDesc.MipLevels = 1;
	depthBufferDesc.ArraySize = 1;
	depthBufferDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
	depthBufferDesc.SampleDesc.Count = 1;
	depthBufferDesc.SampleDesc.Quality = 0;
	depthBufferDesc.Usage = D3D11_USAGE_DEFAULT;
	depthBufferDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
	depthBufferDesc.CPUAccessFlags = 0;
	depthBufferDesc.MiscFlags = 0;

	// Create the texture for the depth buffer using the filled out description.
	result = mDevice->CreateTexture2D(&depthBufferDesc, NULL, &mDepthStencilBuffer);
	CHECK(result);

	return true;
}

bool D3DDevice::SetupDepthStencil()
{
	D3D11_DEPTH_STENCIL_DESC depthStencilDesc;

	// Initialize the description of the stencil state.
	ZeroMemory(&depthStencilDesc, sizeof(depthStencilDesc));

	// Set up the description of the stencil state.
	depthStencilDesc.DepthEnable = true;
	depthStencilDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
	depthStencilDesc.DepthFunc = D3D11_COMPARISON_LESS;

	depthStencilDesc.StencilEnable = true;
	depthStencilDesc.StencilReadMask = 0xFF;
	depthStencilDesc.StencilWriteMask = 0xFF;

	// Stencil operations if pixel is front-facing.
	depthStencilDesc.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
	depthStencilDesc.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_INCR;
	depthStencilDesc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
	depthStencilDesc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS;

	// Stencil operations if pixel is back-facing.
	depthStencilDesc.BackFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
	depthStencilDesc.BackFace.StencilDepthFailOp = D3D11_STENCIL_OP_DECR;
	depthStencilDesc.BackFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
	depthStencilDesc.BackFace.StencilFunc = D3D11_COMPARISON_ALWAYS;

	// Create the depth stencil state.
	HRESULT result = mDevice->CreateDepthStencilState(&depthStencilDesc, &mRenderState.DepthStencilState);
	CHECK(result);

	// Set the depth stencil state.
	mDeviceContext->OMSetDepthStencilState(mRenderState.DepthStencilState, 1);


	D3D11_DEPTH_STENCIL_DESC depthDisabledStencilDesc;
	// Clear the second depth stencil state before setting the parameters.
	ZeroMemory(&depthDisabledStencilDesc, sizeof(depthDisabledStencilDesc));

	// Now create a second depth stencil state which turns off the Z buffer for 2D rendering.  The only difference is 
	// that DepthEnable is set to false, all other parameters are the same as the other depth stencil state.
	depthDisabledStencilDesc.DepthEnable = false;
	depthDisabledStencilDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
	depthDisabledStencilDesc.DepthFunc = D3D11_COMPARISON_LESS;
	depthDisabledStencilDesc.StencilEnable = true;
	depthDisabledStencilDesc.StencilReadMask = 0xFF;
	depthDisabledStencilDesc.StencilWriteMask = 0xFF;
	depthDisabledStencilDesc.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
	depthDisabledStencilDesc.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_INCR;
	depthDisabledStencilDesc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
	depthDisabledStencilDesc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS;
	depthDisabledStencilDesc.BackFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
	depthDisabledStencilDesc.BackFace.StencilDepthFailOp = D3D11_STENCIL_OP_DECR;
	depthDisabledStencilDesc.BackFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
	depthDisabledStencilDesc.BackFace.StencilFunc = D3D11_COMPARISON_ALWAYS;

	// Create the state using the device.
	result = mDevice->CreateDepthStencilState(&depthDisabledStencilDesc, &mRenderState.DepthDisabledStencilState);
	CHECK(result);

	// Initailze the depth stencil view.
	D3D11_DEPTH_STENCIL_VIEW_DESC depthStencilViewDesc;
	ZeroMemory(&depthStencilViewDesc, sizeof(depthStencilViewDesc));

	// Set up the depth stencil view description.
	depthStencilViewDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
	depthStencilViewDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D;
	depthStencilViewDesc.Texture2D.MipSlice = 0;

	// Create the depth stencil view.
	result = mDevice->CreateDepthStencilView(mDepthStencilBuffer, &depthStencilViewDesc, &mDepthStencilView);
	CHECK(result);

	return true;
}

bool D3DDevice::SetupRasterizer()
{
	HRESULT result;

	// Setup the raster description which will determine how and what polygons will be drawn.
	D3D11_RASTERIZER_DESC rasterDesc;
	rasterDesc.AntialiasedLineEnable = false;
	rasterDesc.CullMode = D3D11_CULL_BACK;
	rasterDesc.DepthBias = 0;
	rasterDesc.DepthBiasClamp = 0.0f;
	rasterDesc.DepthClipEnable = true;
	rasterDesc.FillMode = D3D11_FILL_SOLID;
	rasterDesc.FrontCounterClockwise = false;
	rasterDesc.MultisampleEnable = false;
	rasterDesc.ScissorEnable = false;
	rasterDesc.SlopeScaledDepthBias = 0.0f;

	// Create the rasterizer state from the description we just filled out.
	result = mDevice->CreateRasterizerState(&rasterDesc, &mRenderState.RasterizerState);
	CHECK(result);

	// Now set the rasterizer state.
	mDeviceContext->RSSetState(mRenderState.RasterizerState);

	// Setup the viewport for rendering.
	D3D11_VIEWPORT viewport;
	viewport.Width = (float)mResolution.ScreenWidth;
	viewport.Height = (float)mResolution.ScreenHeight;
	viewport.MinDepth = 0.0f;
	viewport.MaxDepth = 1.0f;
	viewport.TopLeftX = 0.0f;
	viewport.TopLeftY = 0.0f;

	mDeviceContext->RSSetViewports(1, &viewport);
	return true;
}

bool D3DDevice::SetupAlphaBlend()
{
	D3D11_BLEND_DESC blendStateDescription;
	
	// Clear the blend state description.
	ZeroMemory(&blendStateDescription, sizeof(D3D11_BLEND_DESC));

	// Create an alpha enabled blend state description.
	/*blendStateDescription.RenderTarget[0].BlendEnable = TRUE;
	blendStateDescription.RenderTarget[0].SrcBlend = D3D11_BLEND_ONE;
	blendStateDescription.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA;
	blendStateDescription.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD;
	blendStateDescription.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ONE;
	blendStateDescription.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ZERO;
	blendStateDescription.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD;
	blendStateDescription.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL;*/

	// Create an alpha enabled blend state description.
	blendStateDescription.RenderTarget[0].BlendEnable = TRUE;
	blendStateDescription.RenderTarget[0].SrcBlend = D3D11_BLEND_ONE;
	blendStateDescription.RenderTarget[0].DestBlend = D3D11_BLEND_ONE;
	blendStateDescription.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD;
	blendStateDescription.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ONE;
	blendStateDescription.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ZERO;
	blendStateDescription.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD;
	blendStateDescription.RenderTarget[0].RenderTargetWriteMask = 0x0f;


	// Create the blend state using the description.
	HRESULT result = mDevice->CreateBlendState(&blendStateDescription, &mRenderState.AlphaEnableBlendingState);
	CHECK(result);

	// Modify the description to create an alpha disabled blend state description.
	blendStateDescription.RenderTarget[0].BlendEnable = FALSE;

	// Create the blend state using the description.
	result = mDevice->CreateBlendState(&blendStateDescription, &mRenderState.AlphaDisableBlendingState);
	CHECK(result);
	return true;
}

ID3D11Device* D3DDevice::GetDevice()
{
	return mDevice;
}

ID3D11DeviceContext* D3DDevice::GetDeviceContext()
{
	return mDeviceContext;
}

ID3D11DepthStencilView* D3DDevice::GetDepthStencilView()
{
	return mDepthStencilView;
}

void D3DDevice::SetBackBufferRenderTarget()
{
	// Bind the render target view and depth stencil buffer to the output render pipeline.
	mDeviceContext->OMSetRenderTargets(1, &mRenderTargetView, mDepthStencilView);
}

void D3DDevice::BeginRender()
{
	if(mDeviceContext)
	{
		mDeviceContext->ClearRenderTargetView(mRenderTargetView, Colors::CornflowerBlue);

		mDeviceContext->ClearDepthStencilView(mDepthStencilView, D3D11_CLEAR_DEPTH, 1.0f, 0);
	}
}

void D3DDevice::EndRender()
{
	if(mGraphicsSettings.VsyncEnabled)	// Present the back buffer to the screen since rendering is complete.
	{	
		mSwapChain->Present(1, 0);		// Lock to screen refresh rate.
	}
	else
	{		
		mSwapChain->Present(0, 0);		// Present as fast as possible.
	}
}

bool D3DDevice::CheckResult(HRESULT result)
{
#ifdef _DEBUG
	if FAILED(result)
	{  
        switch(result)  
        {  
        case E_OUTOFMEMORY:  
            throw D3DException("No Memory!");  
            break;  
        case D3DERR_INVALIDCALL:
			throw D3DException("Invalid Call!");  
            break;
		case D3D11_ERROR_FILE_NOT_FOUND:
			throw D3DException("File Not Found!");
			break;
        default:  
			throw D3DException("HResult Error");  
            break;  
        } 
		return false;
    }
#endif
	return true;
}

D3DMATRIX D3DDevice::GetViewMatrix()
{
	return mViewMatrix;
}

D3DMATRIX D3DDevice::GetWorldMatrix()
{
	return mWorldMatrix;
}

D3DMATRIX D3DDevice::GetProjectionMatrix()
{
	return mProjectionMatrix;
}

D3DMATRIX D3DDevice::GetOrthoMatrix()
{
	return mOrthoMatrix;
}

void D3DDevice::TurnOnAlphaBlending()
{
	float blendFactor[4];
	
	// Setup the blend factor.
	blendFactor[0] = 0.0f;
	blendFactor[1] = 0.0f;
	blendFactor[2] = 0.0f;
	blendFactor[3] = 0.0f;
	
	// Turn on the alpha blending.
	mDeviceContext->OMSetBlendState(mRenderState.AlphaEnableBlendingState, blendFactor, 0xffffffff);
}

void D3DDevice::TurnOffAlphaBlending()
{
	float blendFactor[4];
	
	// Setup the blend factor.
	blendFactor[0] = 0.0f;
	blendFactor[1] = 0.0f;
	blendFactor[2] = 0.0f;
	blendFactor[3] = 0.0f;
	
	// Turn off the alpha blending.
	mDeviceContext->OMSetBlendState(mRenderState.AlphaDisableBlendingState, blendFactor, 0xffffffff);
}

void D3DDevice::TurnZBufferOn()
{
	mDeviceContext->OMSetDepthStencilState(mRenderState.DepthStencilState, 1);
}

void D3DDevice::TurnZBufferOff()
{
	mDeviceContext->OMSetDepthStencilState(mRenderState.DepthDisabledStencilState, 1);
}

LRESULT CALLBACK D3DDevice::MessageHandler(HWND hwnd, UINT umsg, WPARAM wparam, LPARAM lparam)
{
	switch(umsg)
	{
		// Check if a key has been pressed on the keyboard.
		case WM_KEYDOWN:
		{
			// If a key is pressed send it to the input object so it can record that state.
			if(GetInput())
			{
				GetInput()->HandleKeyDown(wparam, lparam);
			}
			return 0;
		}

		// Check if a key has been released on the keyboard.
		case WM_KEYUP:
		{
			// If a key is released then send it to the input object so it can unset the state for that key.
			//m_Input->KeyUp((unsigned int)wparam);
			if(GetInput())
			{
				GetInput()->HandleKeyUp(wparam, lparam);
			}
			return 0;
		}

		// Any other messages send to the default message handler as our application won't make use of them.
		default:
		{
			return DefWindowProc(hwnd, umsg, wparam, lparam);
		}
	}
}


#endif
#ifdef DX_9

POINT CenterWindow(int windowWidth, int windowHeight)
{
	POINT newPoint;
	newPoint.x = (GetSystemMetrics(SM_CXSCREEN) - windowWidth)/2;
	newPoint.y = (GetSystemMetrics(SM_CYSCREEN) - windowHeight)/2;
	return newPoint;
}

D3DDevice::D3DDevice(Engine::NPlatform* owner, HINSTANCE instance, int showCommand)
	:Engine::NDevice(owner)
{
	mWindowsSettings.Instance = instance;
	mGraphicsSettings.ShowCommand = showCommand;
}

D3DDevice::~D3DDevice()
{
}

void D3DDevice::Initialize()
{
	InitWindowHandle();
	InitD3DDevice();
}

void D3DDevice::Deinitialize()
{
}

void D3DDevice::InitWindowHandle()
{
	WNDCLASSEX WindowDesc;

	//Screen width and height set
	mResolution.ScreenWidth = 1280;
	mResolution.ScreenHeight = 720;

	mWindowsSettings.WindowTitle = "Nero Engine DX9";
	mWindowsSettings.WindowClass = "Nero Engine";
	
	// clear out the window class for use
	ZeroMemory(&WindowDesc, sizeof(WNDCLASSEX));

    // fill in the struct with the needed information (PROBABLY DONT NEED TO SAVE)
	WindowDesc.cbSize = sizeof(WNDCLASSEX);
	WindowDesc.style = CS_HREDRAW | CS_VREDRAW /*| CS_NOCLOSE*/;
	WindowDesc.lpfnWndProc = WndProc;
	WindowDesc.cbClsExtra = NULL;
	WindowDesc.cbWndExtra = NULL;
	WindowDesc.hInstance = mWindowsSettings.Instance;
	WindowDesc.hIcon = ::LoadIcon(0, IDI_WINLOGO);
    WindowDesc.hCursor = ::LoadCursor(NULL, IDC_ARROW);
    WindowDesc.hbrBackground = (HBRUSH)COLOR_WINDOW;
	WindowDesc.lpszClassName = mWindowsSettings.WindowClass;
	
    // register the window class
    if (!RegisterClassEx(&WindowDesc))
	{
		MessageBox(NULL, "Error registering class",	"Error", MB_OK | MB_ICONERROR);
		return;
	}

    // create the window and use the result as the handle
	POINT windowLocation = CenterWindow(mResolution.ScreenWidth,mResolution.ScreenHeight);
	mWindowsSettings.WindowHandle = CreateWindowEx (	NULL,
										mWindowsSettings.WindowClass,            // name of the window class
										mWindowsSettings.WindowTitle,            // title of the window
										WS_BORDER,				// window style
										windowLocation.x,		// x-position of the window
										windowLocation.y,		// y-position of the window
										mResolution.ScreenWidth,			// width of the window
										mResolution.ScreenHeight,		   // height of the window
										NULL,					   // we have no parent window, NULL
										NULL,					   // we aren't using menus, NULL
										mWindowsSettings.Instance,   // application handle
										NULL	);				   // used with multiple windows, NULL
	if (!mWindowsSettings.WindowHandle)
	{
		MessageBox(NULL, "Error creating window","Error", MB_OK | MB_ICONERROR);
		return;
	}

	ShowWindow(mWindowsSettings.WindowHandle, mGraphicsSettings.ShowCommand); // display the window on the screen
}

void D3DDevice::InitD3DDevice()
{
	HRESULT hr;
	
	m3DDevice = Direct3DCreate9(D3D_SDK_VERSION);
	
	D3DPRESENT_PARAMETERS PresentParams;
	memset(&PresentParams, 0, sizeof(D3DPRESENT_PARAMETERS));
	
	PresentParams.Windowed = TRUE;
	PresentParams.SwapEffect = D3DSWAPEFFECT_DISCARD;
	PresentParams.hDeviceWindow = mWindowsSettings.WindowHandle;
	PresentParams.BackBufferFormat = D3DFMT_X8R8G8B8;
    PresentParams.BackBufferWidth = mResolution.ScreenWidth;
    PresentParams.BackBufferHeight = mResolution.ScreenHeight;
	PresentParams.EnableAutoDepthStencil = TRUE;
	PresentParams.AutoDepthStencilFormat = D3DFMT_D16;
	PresentParams.PresentationInterval = D3DPRESENT_INTERVAL_DEFAULT;//D3DPRESENT_INTERVAL_IMMEDIATE;
	
	hr = m3DDevice->CreateDevice(  D3DADAPTER_DEFAULT, 
								   D3DDEVTYPE_HAL,
								   mWindowsSettings.WindowHandle, 
								   D3DCREATE_SOFTWARE_VERTEXPROCESSING, 
								   &PresentParams, 
								   &mDevice );

	CHECK(hr)

	// turn on the z-buffer //MOVE!!!!!
	mDevice->SetRenderState(D3DRS_ZENABLE, D3DZB_TRUE); 
}

void D3DDevice::BeginRender()
{
	HRESULT result;
	if(mDevice)
	{
		result = mDevice->Clear(0, NULL, D3DCLEAR_TARGET,  D3DCOLOR_XRGB(100, 149, 237), 1.0f, 0);
		CHECK(result)
		result = mDevice->Clear(0, NULL, D3DCLEAR_ZBUFFER, D3DCOLOR_XRGB(0, 0, 0), 1.0f, 0);
		CHECK(result)
		mDevice->BeginScene();
	}
}

void D3DDevice::EndRender()
{
	HRESULT result;
	if(mDevice)
	{
		mDevice->EndScene();
		result = mDevice->Present(NULL,NULL,NULL,NULL);
		CHECK(result);
	}
}

LPDIRECT3DDEVICE9 D3DDevice::GetDevice()
{
	return mDevice;
}

Resolution D3DDevice::GetResolutionInfo()
{
	return mResolution;
}

WindowsSettings D3DDevice::GetWindowsSettings()
{
	return mWindowsSettings;
}

void D3DDevice::CheckResult(HRESULT result)
{
#ifdef _DEBUG
	if FAILED(result)
	{  
        switch(result)  
        {  
        case E_OUTOFMEMORY:  
            MessageBox(NULL, "No Memory!", "Error", MB_OK);  
            break;  
        case D3DERR_INVALIDCALL:  
            MessageBox(NULL, "Invalid Call!", "Error", MB_OK);  
            break;  
        case D3DXFERR_FILENOTFOUND:  
            MessageBox(NULL, "File Not Found!", "Error", MB_OK);  
            break;  
        case D3DXFERR_PARSEERROR:  
            MessageBox(NULL, "Parse Error!", "Error", MB_OK);  
            break;  
        default:  
            MessageBox(NULL, "No Effect!", "Error", MB_OK);  
            break;  
        }  
    }
#endif
}
#endif

LRESULT CALLBACK D3DDevice::WndProc(HWND windowHandle, UINT message, WPARAM wParam,LPARAM lParam)
{
    switch(message)	// sort through and find what code to run for the message given
    {
		case WM_CLOSE:
			{
				PostQuitMessage(0);		
				return 0;
			}
        case WM_DESTROY:				
			{
				PostQuitMessage(0);		
				return 0;
			}
		default:
			{
				return GetPlatform()->GetDevice()->As<D3DDevice>()->MessageHandler(windowHandle, message, wParam, lParam);
			}
    }
}